//
//  BDJTabBar.m
//  BuDeJie
//
//  Created by Guo Rui on 2017/9/19.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "BDJTabBar.h"

@interface BDJTabBar ()
@property (strong, nonatomic) UIButton *plusButton;

@property (weak, nonatomic) UIControl *previousTabBarButton;

@end

@implementation BDJTabBar

- (UIButton *)plusButton
{
    if (!_plusButton) {
        _plusButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_plusButton setImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:UIControlStateNormal];
        [_plusButton setImage:[UIImage imageNamed:@"tabBar_publish_click_icon"] forState:UIControlStateHighlighted];
        [self addSubview:_plusButton];
    }
    return _plusButton;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    NSInteger count = self.items.count;
    
    CGFloat x = 0;
    CGFloat w = self.width / (count + 1);
    CGFloat h = self.height;
    int i = 0;
    
    for (UIControl *subview in self.subviews) {
        if ([subview isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            if (i == 0 && self.previousTabBarButton == nil) {
                self.previousTabBarButton = subview;
            }
            
            if (i == 2) {
                self.plusButton.frame = CGRectMake(i * w, 0, w, h);
                i += 1;
            }
            x = i * w;
            subview.frame = CGRectMake(x, 0, w, h);
            
            i++;
            
            [subview addTarget:self action:@selector(tabBarClick:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
}

- (void)tabBarClick:(UIControl *)tabBarButton
{
    if (self.previousTabBarButton == tabBarButton) {
        [[NSNotificationCenter defaultCenter] postNotificationName:BDJTabBarButtonDidRepeatClickNotification object:nil];
    }
    self.previousTabBarButton = tabBarButton;
}

@end
